// Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
// This source file is part of the Cangjie project, licensed under Apache-2.0
// with Runtime Library Exception.
//
// See https://cangjie-lang.cn/pages/LICENSE for license information.

/**
 * @file
 *
 * This file declares the IncrementalCompilerInstance, which performs the incremental compile flow.
 */

#ifndef CANGJIE_FRONTEND_INCREMENTALCOMPILERINSTANCE_H
#define CANGJIE_FRONTEND_INCREMENTALCOMPILERINSTANCE_H

#include "cangjie/FrontendTool/DefaultCompilerInstance.h"
#include "cangjie/IncrementalCompilation/CachedMangleMap.h"
#include "cangjie/IncrementalCompilation/IncrementalScopeAnalysis.h"
#include "cangjie/IncrementalCompilation/IncrementalCompilationLogger.h"
#include "cangjie/Parse/ASTHasher.h"

namespace Cangjie {

class IncrementalCompilerInstance : public DefaultCompilerInstance {
public:
    IncrementalCompilerInstance(CompilerInvocation& invocation, DiagnosticEngine& diag)
        : DefaultCompilerInstance(invocation, diag)
    {
    }
    ~IncrementalCompilerInstance() override;

    bool InitCompilerInstance() override;

    bool PerformIncrementalScopeAnalysis() override;
    bool PerformSema() override;
    bool PerformOverflowStrategy() override;
    bool PerformDesugarAfterSema() override;
    bool PerformGenericInstantiation() override;
    bool PerformMangling() override;
    bool PerformCHIRCompilation() override;
    bool PerformCodeGen() override;
    virtual bool PerformCjoAndBchirSaving() override;

    CachedMangleMap cacheMangles;
    // Store the struct types who's layout has been changed and needs to be regenerated its IR.
    // NOTE: since class layout is generated in separate step, we don not need to collect them.
    //       And enum types have fixed layout for non-class or same as class type generation, it also can be ignored.
    std::unordered_set<Ptr<const AST::StructTy>> changedTypes;

private:
    std::unordered_set<Ptr<AST::Decl>> declsToBeReCompiled;
    // stored mangled name before sema, generated by ASTDiff
    std::list<std::string> rawIncrRemovedDecls;

    void SaveCompilationResult(Cangjie::IncreResult&& result);
    void LoadCachedCodegenResult() const;
    void UpdateCachedInfo() override;
    void UpdateCHIROptEffectMap();
};
} // namespace Cangjie

#endif // CANGJIE_FRONTEND_INCREMENTALCOMPILERINSTANCE_H
